package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.Utils.AliyunSmsUtil;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    //发送验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody Map<String,String> user, HttpSession httpSession) {
        String phoneNum = user.get("phone");
        if (BeanUtil.isEmpty(phoneNum)){
            return R.error("您输入的手机号不正确");
        }
        //生成一个六位随机数
        String code = RandomUtil.randomNumbers(6);
        log.info("code={}" + code);
        //AliyunSmsUtil.sendSms(phoneNum,code);
        //将验证码保存在session中
        httpSession.setAttribute(phoneNum,code);
        return R.success("验证码发送成功");
    }

    //用户登录
    @PostMapping("/login")
    public R<String> loginUser(@RequestBody Map<String,String> user,HttpSession httpSession){
        String code = user.get("code");
        String phoneNum = user.get("phone");
        //获得验证码
        String yzm = (String) httpSession.getAttribute(phoneNum);
        if (yzm!=null && yzm.equals(code)){
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phoneNum);
            //检查是否为新用户
            User loginuser = userService.getOne(lqw);
            if (loginuser == null){
                //创建user对象
               loginuser = new User();
               loginuser.setPhone(phoneNum);
               loginuser.setStatus(1);
               userService.save(loginuser);
            }
            httpSession.setAttribute("loginUser",loginuser);
            return R.success("登陆成功");
        }
        return R.error("登陆失败");
    }

    //退出登录
    @PostMapping("/loginout")
    public R<String> logout(HttpSession httpSession){
        //将存的session删除
        httpSession.removeAttribute("loginUser");
        return R.success("退出成功");
    }
}
